<?php

namespace app\unify\middleware;

use app\Request;
use app\unify\model\Api as ApiModel;
use app\unify\model\RoleAuth;
use app\unify\model\User;
use Kayex\HttpCodes;
use thans\jwt\exception\TokenBlacklistGracePeriodException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\middleware\BaseMiddleware;

class Authority extends BaseMiddleware
{
    /**
     * @throws \Exception
     */
    public function handle(Request $request, \Closure $next)
    {

        //判断当前路由是不是匿名的，如果是则不加权限验证。
        $url = $request->baseUrl();

        $api = ApiModel::where([
            'path' => $url
        ])->findOrEmpty();


        if ($api->isEmpty()) {
            throw new \Exception('拒绝访问，请求地址不存在。');
        }

        if ($api['anonymous'] == ApiModel::ANONYMOUS_TRUE) {
            return $next($request);
        }


        // 验证token
        try {
            if($request->param('token')){
                $this->auth->setToken($request->param('token'));
            }

            $this->auth->auth();

        } catch (TokenExpiredException $e) { // 捕获token过期
            // 尝试刷新token
            try {
                $this->auth->setRefresh();
                $token = $this->auth->refresh();

                // $payload = $this->auth->auth(false);
                // $request->uid = $payload['uid'];

                $response = $next($request);
                return $this->setAuthentication($response, $token);
            } catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期
                // $payload = $this->auth->auth(false);
                // $request->uid = $payload['uid'];

                return $next($request);
            }
        } catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期
            // $payload = $this->auth->auth(false);
            // $request->uid = $payload['uid'];
        }

        $user = User::current();
        if($user->isEmpty()){
            throw new \Exception('用户不存在', HttpCodes::HTTP_FORBIDDEN);
        }

        if ($user['status'] == User::STATUS_DISABLE) {
            throw new \Exception('用户已被禁用', HttpCodes::HTTP_FORBIDDEN);
        }

        if ($user->isAdmin()) {
            return $next($request);
        }

        //判断平台是否匹配
        if(!in_array($user['platform'], explode(',', $api['platform']))){
            throw new \Exception('拒绝访问，请刷新页面重试。');
        }

        if(!config('base.site_status')){
            throw new \Exception('站点暂停服务，请联系管理员', HttpCodes::HTTP_BAD_REQUEST);
        }

        //检查API是否有关联权限，如果没有则不用验权
        $authIds = $api->apiAuths->column('auth_id');
        if(empty($authIds)){
            return $next($request);
        }


        $roleIds = $user->userRoles->column('role_id');


        if (RoleAuth::where([
            ['auth_id', 'in', $authIds],
            ['role_id', 'in', $roleIds]
        ])->select()->isEmpty()) {
            throw new \Exception("暂无权限");
        }

        return $next($request);
    }

}